<?php

class userModel extends Model {

	const USERINFO_KEY = 'cs_user_';
	const TYPE_NORMAL = 1;
	const TYPE_VIRTUAL = 2;

	public function validata($data) {
		$result = Validation::rule(
			array(Validation::isMust($data['mobile']), '手机号不能为空'),
			array(Validation::isMust($data['password']), '密码不能为空'),
			array(Validation::isMobile($data['mobile']), '手机号码填写有误'),
			array(Validation::isLength($data['password'], 8, 12), '密码长度在8~12位')
		);
		return $result;
	}

	public function getAllStatus() {
		return [1 => '正常', 2 => '屏蔽'];
	}

	public function getVirtualList() {
		return $this->getAll('type=?', self::TYPE_VIRTUAL);
	}

	public function login($user_info) {
		$Encrypt = Doit::singleton('Encrypt');
		$key = md5(Configure::get('security_key') . 'user');
		$ticket = $Encrypt->encode(implode('\t', array($user_info['uid'], time())), $key);

		return $ticket;
	}

	public function getLoginInfo($userInfo) {
		if (!isset($userInfo['uid']) || !$userInfo['uid']) {
			return false;
		}
		$userInfo = $this->findById($userInfo['uid']);
		$userInfo['ticket'] = $this->login($userInfo);
		return self::buildBaseUserInfo($userInfo);
//        return [
		//            'uid' => intval($userInfo['uid']),
		//            'nickname' => strval($userInfo['nickname']),
		//            'avatar' => strval($userInfo['avatar']),
		//            'ticket' => strval($userInfo['ticket'])
		//        ];
		//        return $this->formateData($userInfo);
	}

	public static function buildBaseUserInfo($userInfo) {
		if (isset($userInfo['ticket'])) {
			return [
				'uid' => intval($userInfo['uid']),
				'nickname' => strval($userInfo['nickname']),
				'avatar' => strval($userInfo['avatar']),
				'ticket' => strval($userInfo['ticket']),
			];
		} else {
			return [
				'uid' => intval($userInfo['uid']),
				'nickname' => strval($userInfo['nickname']),
				'avatar' => strval($userInfo['avatar']),
			];
		}
	}

	public function getUserInfo($userInfo) {
		return $userInfo;
	}

	public function logout() {
		return true;
	}

	public static function checkLogin($ticket = '') {
		$ticket = $ticket ? $ticket : Request::getParams('ticket');
		if (!$ticket) {
			return false;
		}
		$Encrypt = Doit::singleton('Encrypt');
		$user_info = array(
			'uid' => '',
			'logintime' => '',
		);
		$key = md5(Configure::get('security_key') . 'user');
		$idString = $Encrypt->decode($ticket, $key);
		if (isset($idString) && $idString && strpos($idString, '\t')) {
			list($user_info['uid'], $user_info['logintime']) = explode('\t', $idString);
			if ($user_info['uid']) {
				return $user_info;
			}
		}
		return false;
	}

	public function updateById($uid, $data) {
		$this->update($data, 'uid=?', array($uid));
		Cache_Memcache::getInstance()->delete(self::USERINFO_KEY . $uid);
		return true;
	}

	public function deleteCacheById($uid) {
		Cache_Memcache::getInstance()->delete(self::USERINFO_KEY . $uid);
		return true;
	}

	public function findById($uid) {
//        if (!$user_info = Cache_Memcache::getInstance()->get(self::USERINFO_KEY . $uid)) {
		if (!$user_info = $this->getOne('uid=?', array($uid))) {
			return false;
		}
		$user_info = $this->formateData($user_info);
//            Cache_Memcache::getInstance()->set(self::USERINFO_KEY . $uid, $user_info);
		//        }
		return $user_info;
	}

	public function encodeVerifyToken($data) {
		//@todo
		$Encrypt = Doit::singleton('Encrypt');
		$key = md5(Configure::get('security_key'));
		return $Encrypt->encode(implode('\t', array($data['id'], time())), $key);
	}

	public function decodeVerifyToken($verify_token) {
		$Encrypt = Doit::singleton('Encrypt');
		$data = array(
			'id' => '',
			'time' => '',
		);
		$key = md5(Configure::get('security_key'));
		$idString = $Encrypt->decode($verify_token, $key);
		if (isset($idString) && $idString && strpos($idString, '\t')) {
			list($data['id'], $data['time']) = explode('\t', $idString);
			if ($data['id']) {
				return $data;
			}
		}
		return false;
	}

	public function countByDay() {
		$sql = "select date(`add_time`) as total from `wf_user` GROUP BY date(`add_time`)";
		$result = $this->query($sql)->fetchAll();
		return count($result);
	}

	public function groupByDay($page, $page_size) {
		$limit = ($page - 1) * $page_size;
		$sql = "select date(`add_time`) as day,count(`uid`) as total from `wf_user` GROUP BY date(`add_time`) limit {$limit}, {$page_size}";
		$result = $this->query($sql)->fetchAll();
		$data = array();
		if ($result) {
			foreach ($result as $row) {
				$data[$row['day']] = $row['total'];
			}
		}
		return $data;
	}

	public function formateData($data) {
		if (!$data) {
			return array();
		}
		foreach ($data as $key => $value) {
			if (is_array($value)) {
				$data[$key] = $this->formateData($value);
			} else {
				switch ($key) {
				case 'uid':
				case 'sex':
				case 'status':
				case 'points':
				case 'fans_total':
				case 'follow_total':
				case 'collect_total':
					$data[$key] = (int) $value;
					break;
				case 'cash':
					$data[$key] = floatval($value);
					break;
				default:
					$data[$key] = (string) $value;
				}
			}
		}
		return $data;
	}

	public function getList($where, $value, $uid, $page, $pageSize) {
		$resultData = [
			'page' => intval($page),
			'pageSize' => intval($pageSize),
			'list' => [],
		];
		$list = $this->limit(($page - 1) * $pageSize, $pageSize)->order('uid desc')->getAll($where, $value);
		$resultData['list'] = $this->buildUserInfo($list, $uid);
		return $resultData;
	}

	private function buildUserInfo($list, $uid) {
		if (!$list) {
			return [];
		}
		$result = $uids = $userData = [];
		foreach ($list as $row) {
			$uids[] = $row['uid'];
		}
		$uids = implode(',', $uids);
		$myCollect = $this->query("select to_uid from wf_user_relate where uid={$uid}")->fetchAll();
		$myCollectUids = [];
		if ($myCollect) {
			foreach ($myCollect as $row) {
				$myCollectUids[] = $row['to_uid'];
			}
		}
		unset($userInfoList);
		foreach ($list as $info) {
			if (in_array($info['uid'], $myCollectUids)) {
				$isfans = 1;
			} else {
				$isfans = 0;
			}
			$result[] = [
				'uid' => intval($info['uid']),
				'nickname' => strval($info['nickname']),
				'avatar' => strval($info['avatar']),
				'is_fans' => $isfans,
				'fans_total' => intval($info['fans_total']),
				'dynamic_total' => intval($info['dynamic_total']),
				'autograph' => $info['autograph'],
			];

		}
		return $result;
	}
}
